// app/middleware/response.js
module.exports = function() {
	let codeMap = {
		'-1': '请求失败',
		200: '请求成功',
		401: '权限校验失败',
		403: 'Forbidden',
		404: 'URL资源未找到',
		422: '参数校验失败',
		500: '服务器错误'
	};

	function isString(obj){
		return obj===obj+'';
	}

	const successMsg = codeMap[200];
	const failMsg = codeMap[-1];

	return async (ctx, next) => {
		ctx.success = (data = null, message = successMsg) => {
			if (isString(data)) {
				message = data;
				data = null
			}
			ctx.status = 200;
			ctx.body = {
				code: 200,
				success: true,
				message,
				data
			}
		};
		ctx.fail = (code = -1, message = '', error = null) => {
			if (isString(code)) {
				error = message || null;
				message = code;
				code = -1
			}
			const body = {
				code,
				success: false,
				message: message || codeMap[code] || failMsg
			};
			if (error) body.error = error;
			ctx.status = code === -1 ? 200 : code;
			ctx.body = body
		};

		await next()
	}
};
